﻿using System;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Pfz.Drawing.Wpf.Extensions
{
	/// <summary>
	/// This class add the CreateBitmapSource methods to the ManagedBitmap&lt;byte&gt;
	/// and ManagedBitmap&lt;Rgb24&gt;.
	/// </summary>
	public static class WpfManagedBitmapExtensions
	{
		/// <summary>
		/// Creates a grayscale bitmap-source from the this managed bitmap.
		/// </summary>
		public static BitmapSource CreateBitmapSource(this ManagedBitmap<byte> managedBitmap)
		{
			if (managedBitmap == null)
				throw new ArgumentNullException("managedBitmap");
			
			var pixelArray = managedBitmap.PixelArray;
			unsafe
			{
				fixed(void *buffer = pixelArray)
				{
					BitmapSource result = BitmapSource.Create(managedBitmap.Width, managedBitmap.Height, 96, 96, PixelFormats.Gray8, null, (IntPtr)buffer, pixelArray.Length, managedBitmap.Width);
					return result;
				}
			}
		}
		
		/// <summary>
		/// Creates an indexed-8 bitmap-source from this ManagedBitmap.
		/// Uses the given palette.
		/// </summary>
		public static BitmapSource CreateBitmapSource(this ManagedBitmap<byte> managedBitmap, BitmapPalette palette)
		{
			if (managedBitmap == null)
				throw new ArgumentNullException("managedBitmap");
			
			if (palette == null)
				throw new ArgumentNullException("palette");
			
			var pixelArray = managedBitmap.PixelArray;
			unsafe
			{
				fixed(void *buffer = pixelArray)
				{
					BitmapSource result = BitmapSource.Create(managedBitmap.Width, managedBitmap.Height, 96, 96, PixelFormats.Indexed8, palette, (IntPtr)buffer, pixelArray.Length, managedBitmap.Width);
					return result;
				}
			}
		}
		
		/// <summary>
		/// Creates a bitmap source from this 24-bit ManagedBitmap.
		/// </summary>
		public static BitmapSource CreateBitmapSource(this ManagedBitmap<Rgb24> managedBitmap)
		{
			if (managedBitmap == null)
				throw new ArgumentNullException("managedBitmap");
			
			var pixelArray = managedBitmap.PixelArray;
			unsafe
			{
				fixed(void *buffer = pixelArray)
				{
					BitmapSource result = BitmapSource.Create(managedBitmap.Width, managedBitmap.Height, 96, 96, PixelFormats.Bgr24, null, (IntPtr)buffer, pixelArray.Length * 3, managedBitmap.Width * 3);
					return result;
				}
			}
		}
	}
}
